package com.lmscn.lms.api.controller;

import com.jfinal.core.Controller;
import com.lmscn.lms.api.model.*;
import com.lmscn.lms.api.util.JsonKit;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LearningController  extends Controller {

    /**
     * 个人档案
     */
    public void myLearningReport() {
        Integer year = getParaToInt("year");
        String group = getPara("group");
        Long studentId = getParaToLong("studentId");

        StudyPlan studyPlan = StudyPlan.dao.getStudyPlan(year, group);

        if(studyPlan != null){
            Map<String,Object> map = new HashMap<>();
            //查询学习计划课程--选修
            Map XstudyPlanCourseRecordListMap = this.getStudyFileCourseRecordList(year, studentId, studyPlan.getLong("id"),"0");
            List<StudyFileCourseRecord> XstudyPlanCourseRecordList = (List<StudyFileCourseRecord>)XstudyPlanCourseRecordListMap.get("list");
            map.put("XstudyPlanCourseRecordList", XstudyPlanCourseRecordList);
            map.put("Xtotal",XstudyPlanCourseRecordListMap.get("total"));


            //查询学习计划课程--必修
            Map BstudyPlanCourseRecordListMap = this.getStudyFileCourseRecordList(year, studentId, studyPlan.getLong("id"),"1");
            List<StudyFileCourseRecord> BstudyPlanCourseRecordList = (List<StudyFileCourseRecord>)BstudyPlanCourseRecordListMap.get("list");
            map.put("BstudyPlanCourseRecordList", BstudyPlanCourseRecordList);
            map.put("Btotal", BstudyPlanCourseRecordListMap.get("total"));


            //学习计划考试列表
            Map studyPlanCourseExamRecordListMap = this.getStudyFileStudyPlanExamRecordList(studentId, studyPlan.getLong("id"), Integer.valueOf(year));
            List<StudyFileStudyPlanExamRecord> studyPlanCourseExamRecordList = (List<StudyFileStudyPlanExamRecord>)studyPlanCourseExamRecordListMap.get("list");
            map.put("studyPlanCourseExamRecordList", studyPlanCourseExamRecordList);
            map.put("Etotal", studyPlanCourseExamRecordListMap.get("total"));
            Float total = Float.valueOf(XstudyPlanCourseRecordListMap.get("total").toString())+Float.valueOf(BstudyPlanCourseRecordListMap.get("total").toString())+Float.valueOf(studyPlanCourseExamRecordListMap.get("total").toString());
            map.put("total", total);

            renderJson(JsonKit.mapToJson(map, map.size()));
        }
        else {
            renderJson(JsonKit.mapToJson(null, 0));
        }
    }



    private Map getStudyFileCourseRecordList(int year,Long studentId,Long studyPlanId,String courseType) {
        List<StudyFileCourseRecord> recordList = new ArrayList<StudyFileCourseRecord>();

        List<CourseStudent> courselist = new ArrayList<CourseStudent>();
        if(courseType.equals("0")){//选修课
            List<CourseStudent> list2 = findStudyfileElectiveCourseList(studentId, studyPlanId);
            courselist.addAll(list2);
        }else if(courseType.equals("1")){//必修课
            List<CourseStudent> list1 = findStudyfileCompulsoryCourseList(studentId, studyPlanId);
            courselist.addAll(list1);
        }else if(courseType.equals("2")){//选修课+必修课
            List<CourseStudent> list2 = findStudyfileElectiveCourseList(studentId, studyPlanId);
            courselist.addAll(list2);
            List<CourseStudent> list1 = findStudyfileCompulsoryCourseList(studentId, studyPlanId);
            courselist.addAll(list1);
        }

        Float total = 0f;
        for(int i = 0; i < courselist.size(); i++){
            StudyFileCourseRecord record = new StudyFileCourseRecord();
            CourseStudent courseStudent = courselist.get(i);

            Long courseId = courseStudent.getLong("course_id");
            CourseBase courseBase = CourseBase.dao.findById(courseId);
            CourseLearningSetting courseLearningSetting = CourseLearningSetting.dao.findByCourseId(courseId);

            if (courseBase == null || courseLearningSetting == null) {
                continue;
            }

            record.setStudyPlanId(studyPlanId);
            record.setCourseName(courseBase.getStr("name"));
            record.setCoursePeriod(courseLearningSetting.getFloat("period") == null ? null : courseLearningSetting.getFloat("period"));
            record.setCourseStudentId(courseStudent.getLong("id"));
            record.setCourseStudent(courseStudent);
            record.setCourseType(courseStudent.getStr("course_type"));
            record.setFinishedTime(courseStudent.getDate("finished_time"));
            record.setLearnedStatus(courseStudent.getInt("learned_status"));
            record.setScore(courseStudent.getInt("score"));
            record.setSelectedTime(courseStudent.getDate("create_time"));
            record.setTeacherName(courseBase.getStr("teacher_name"));
            recordList.add(record);
            if(courseStudent.getInt("learned_status")==1){
                total+=courseLearningSetting.getFloat("period") == null ? 0 : courseLearningSetting.getFloat("period");
            }
        }
        Map finalMap = new HashMap();
        finalMap.put("list", recordList);
        finalMap.put("total", total);
        return finalMap;
    }

    /**
     * 获取我的选修课学习情况列表（学习档案页面）
     * @param studentId
     * @param studyplanId
     * @return
     * @throws ParseException
     */
    private List<CourseStudent> findStudyfileElectiveCourseList(Long studentId,
                                                                Long studyplanId) {
//        query.setSortColumns(" t.learnedStatus desc, t.finishedTime desc");

        List<CourseStudent> list =CourseStudent.dao.findCourseStudentList(studentId,studyplanId,"studyplan",-1,0);
        return list;
    }


    private List<CourseStudent> findStudyfileCompulsoryCourseList(Long studentId,
                                                                  Long studyplanId) {
//        query.setSortColumns(" t.learnedStatus desc, t.finishedTime desc");
        List<CourseStudent> list =CourseStudent.dao.findCourseStudentList(studentId,studyplanId,"studyplan",-1,1);
        return list;
    }


    public Map getStudyFileStudyPlanExamRecordList(Long studentId, Long studyPlanId, int year){
        //获取学员已经参加的年度学习计划考试列表
        List<Exam> list = Exam.dao.getJoinedYearStudyPlanExamList(studentId, year);
        //学习计划内参加的课程考试
        List<StudyFileStudyPlanExamRecord> recordList = new ArrayList<StudyFileStudyPlanExamRecord>();
        Float total = 0f;
        if(list != null && list.size() > 0){
            for(Exam exam:list){
                StudyFileStudyPlanExamRecord record = new StudyFileStudyPlanExamRecord();
                record.setExamId(exam.getLong("id"));
                record.setExamName(exam.getStr("title"));
                record.setStudentId(studentId);
                record.setStudyPlanId(studyPlanId);
                //已完成的考试
                TestpaperResult result = TestpaperResult.dao.getFinishedTestpaperResult1(exam.getStr("target_type"),exam.getLong("id"),studentId);

                //未提交答卷
                if(result == null){
                    result = TestpaperResult.dao.getTestpaperResult1(exam.getStr("target_type"),exam.getLong("id"),studentId);
                    record.setStatus("notsubmit");
                    record.setSubmitTime(null);
                    record.setExamScore(null);
                }
                //已提交答卷
                else{
                    boolean passed = TestpaperResult.dao.passedExam(exam,studentId);
                    if(passed){
                        record.setStatus("passed");
                        total+=exam.getFloat("course_period");
                    }else{
                        record.setStatus("notpassed");
                    }
                    record.setSubmitTime(result.getDate("end_time"));
                    record.setExamScore(result.getInt("score"));
                }

                recordList.add(record);

            }
        }
        Map finalMap = new HashMap();
        finalMap.put("list", recordList);
        finalMap.put("total", total);
        return finalMap;
    }
}
